package com.dwx.gmall.product.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dwx.gmall.model.product.SpuImage;
import com.dwx.gmall.model.product.SpuInfo;
import com.dwx.gmall.model.product.SpuSaleAttr;
import com.dwx.gmall.model.product.SpuSaleAttrValue;
import com.dwx.gmall.product.mapper.SpuImageMapper;
import com.dwx.gmall.product.mapper.SpuInfoMapper;
import com.dwx.gmall.product.mapper.SpuSaleAttrMapper;
import com.dwx.gmall.product.mapper.SpuSaleAttrValueMapper;
import com.dwx.gmall.product.service.SpuInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.web.context.ContextLoaderListener;

import java.util.List;

@Service
public class SpuInfoServiceImpl extends ServiceImpl<SpuInfoMapper, SpuInfo> implements SpuInfoService {

    @Autowired
    SpuImageMapper spuImageMapper;
    @Autowired
    SpuSaleAttrMapper spuSaleAttrMapper;
    @Autowired
    SpuSaleAttrValueMapper spuSaleAttrValueMapper;
    /**
     * @param spuInfo
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean saveSpuInfo(SpuInfo spuInfo) {
        baseMapper.insert(spuInfo);
        Long id = spuInfo.getId();
        List<SpuImage> spuImageList = spuInfo.getSpuImageList();
        if(!CollectionUtils.isEmpty(spuImageList)){
            for (SpuImage spuImage : spuImageList) {
                spuImage.setSpuId(id);
                spuImageMapper.insert(spuImage);
            }
        }
        List<SpuSaleAttr> spuSaleAttrList = spuInfo.getSpuSaleAttrList();
        if(!CollectionUtils.isEmpty(spuSaleAttrList)){
            for (SpuSaleAttr spuSaleAttr : spuSaleAttrList) {
                spuSaleAttr.setSpuId(id);
                spuSaleAttrMapper.insert(spuSaleAttr);
                String saleAttrName = spuSaleAttr.getSaleAttrName();
                List<SpuSaleAttrValue> spuSaleAttrValueList = spuSaleAttr.getSpuSaleAttrValueList();
                for (SpuSaleAttrValue spuSaleAttrValue : spuSaleAttrValueList) {
                    spuSaleAttrValue.setSpuId(id);
                    spuSaleAttrValue.setSaleAttrName(saleAttrName);
                    spuSaleAttrValueMapper.insert(spuSaleAttrValue);
                }
            }
        }
        return true;
    }
}
